package com.yzp.controller;

import com.yzp.entity.User;
import com.yzp.model.PageResult;
import com.yzp.model.Result;
import com.yzp.model.StatusCode;
import com.yzp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * @title: UserController
 * @Author: yzp
 * @Date: 2019/7/22 16:47
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable("id") Long id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findOne(id));
    }

    @GetMapping("/findByName")
    public Result findOne(String name) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findByName(name));
    }

    @GetMapping("/findByJpql")
    public Result findByJpql(String name, Long id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findByJPQL(name, id));
    }

    @GetMapping("/findByPage")
    public Result findByPage(String name, @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "2") Integer size) {
        Page dPage = userService.findByPage(name, page, size);
        return new Result(true, StatusCode.OK, "查询成功",
                new PageResult<User>(dPage.getTotalElements(), dPage.getContent()));
    }

    @PostMapping
    public Result save(@RequestBody User user) {
        userService.save(user);
        return new Result(true, StatusCode.OK, "添加成功");
    }

}
